<?php
App::uses('CakeSchema','Model');
App::uses('Folder','Utility');
App::uses('File','Utility');
class ToolsController extends AppController {

    public $name = 'Tools';
    
    public $components = array('DbBackup');
    
    public $uses = array();//This will allow you to use a controller without a need for a corresponding Model file.

    function admin_index() {
        $this->pageTitle = __('Tools');
    }
    /**
     * SAE环境初始化。
     */
    function admin_saeinit(){
        
    }
    
    public function admin_uploadoss(){
        
        if(!empty($_POST)) {
            $this->autoRender = false;
            App::uses('CrawlUtility', 'Utility');
            
            $object_name = $_POST['data']['Uploadfile']['object_name'];
            if( strpos($object_name,'.php') !== false ) {
                echo 'php not allowed';
                exit;
            }
            $file_path = $_FILES['data']['tmp_name']['Uploadfile']['file'];
            $mime = $_FILES['data']['type']['Uploadfile']['file'];
            
            $bucket = $_POST['data']['Uploadfile']['bucket'];
            
            echo "==$file_path, $object_name,true,false,$mime==$bucket<br/>";
            $ret =  CrawlUtility::saveToAliOss($file_path, $object_name,true,false,$mime,array('bucket_name'=>$bucket));
            var_dump($ret);
        }
    }
    
    public function admin_batchSetImageHeight($model='EditorStyle',$page = 1){
        if($model == 'EditorStyle') {
        	$height = 24;
            $this->loadModel('EditorStyle');
            $images = $this->EditorStyle->find('all',array(
                //'conditions' => array('cate_id'=>53),
                'conditions' => array('cover_height >'=> 0),
        		'limit' => 50,
        		'page' => $page,
            ));
            foreach($images as $image) {
                $size  = @getimagesize($image[$model]['coverimg']);
                
                if( $image[$model]['cover_height'] ) {
                    $height = $image[$model]['cover_height'];
                }
                
                if( $size ) {
		            echo "=={$image[$model]['id']}=={$size[1]}==<br/>";
                    /*if($size[1] < $height) {
                        // 高度小的图片，将高度改成0，使用自动的宽度
                        $this->EditorStyle->updateAll(
                            array('cover_height' => 0),
                            array('id'=> $image[$model]['id'] )
                        );
                    }
                    else{*/
                        $this->EditorStyle->updateAll(
                            //array('cover_height' => $height),
                            array('cover_width' => $size[0]*$height/$size[1],'cover_height' => 0),
                            array('id'=> $image[$model]['id'] )
                        );
                    //}
                }
            }
    	    if(count($images) > 0) {
    	       $this->__message('next page','/admin/tools/batchSetImageHeight/EditorStyle/'.($page+1));
    	    }
        }
        elseif($model == 'Image') {
        	$height = 32;
            $this->loadModel('Image');
            $images = $this->Image->find('all',array(
                'conditions' => array('height >'=>0),
        		'limit' => 50,
        		'page' => $page,
            ));
            foreach($images as $image) {
                $size  = @getimagesize($image[$model]['coverimg']);
                if( $image[$model]['height'] ) {
                    $height = $image[$model]['height'];
                }
                if( $size ) {
		              echo "=={$image[$model]['id']}=={$size[1]}==<br/>";
                    /*if($size[1] < $height) {
                        // 高度小的图片，将高度改成0，使用自动的宽度
                        $this->Image->updateAll(
                            //array('height' => 0),
                            
                            array('id'=> $image[$model]['id'] )
                        );
                    }
                    else{*/
                        $this->Image->updateAll(
                            //array('height' => $height),
                            array('width' => $size[0]*$height/$size[1],'height' => 0),
                            array('id'=> $image[$model]['id'] )
                        );
                    //}                    
                }
            }
    	    if(count($images) > 0){
    	       $this->__message('next page','/admin/tools/batchSetImageHeight/Image/'.($page+1));
    	    }
    	}
        echo 'over';
        exit;
    }
    
    function admin_priority($modelClass='EditorStyle') {
    	$this->loadModel($modelClass);
    	
    	if(!empty($_POST)) {
    		foreach ($_POST as $m => $order) {
    			$count = count($order);
    			foreach ($order as $k => $tid) {
    				// save 函数多进行了一次数据库 select操作，不如update节省数据库连接
    				$this->{$modelClass}->updateAll(array($modelClass.'.priority' => ($count - $k)*10), array($modelClass.'.id' => $tid));
    			}
    		}
    		exit(1);
    	}
    	
    	$conditions = getSearchOptions($_GET, $modelClass);
    	$datalist = $this->{$modelClass}->find('all', array(
    			'order' => array('priority desc', 'id asc'),
    			'conditions' => $conditions,
    	));
    	$this->set('modelClass',$modelClass);
    	$this->set('datalist', $datalist);
    }
    
    function admin_stats($model='User',$month = '') {
    	$this->loadModel($model);
    	
    	$keys = array_keys($this->{$model}->schema());
    	$conditions = array();
    	foreach($keys as $k) {
    	    if($_GET[$k]) {
    	        $conditions[$k] = $_GET[$k];
    	    }
    	}
    	
    	
    	$today_count = $this->{$model}->find('count',array(
    		'conditions' => array_merge($conditions,array('created >=' => date('Y-m-d'))),
    	    'recursive' => -1,
    	));
    	$yestoday_count = $this->{$model}->find('count',array(
    	    'conditions' => array_merge($conditions,array('created >=' => date('Y-m-d',strtotime('-1 days')),'created <' => date('Y-m-d') )),
    	    'recursive' => -1,
    	));
    	$week = date('N'); $start_week_day = date('Y-m-d',strtotime('-'.($week-1).' days'));
    	
    	$week_count = $this->{$model}->find('count',array(
    		'conditions' => array_merge($conditions,array('created >=' => $start_week_day)),
    	    'recursive' => -1,
    	));
    	$month_count = $this->{$model}->find('count',array(
    		'conditions' => array_merge($conditions,array('created >=' => date('Y-m'))),
    	    'recursive' => -1,
    	));
    	$last_month_count = $this->{$model}->find('count',array(
    		'conditions' => array_merge($conditions,array('created >=' => date('Y-m',strtotime('-1 month')),'created <' => date('Y-m') )),
    	    'recursive' => -1,
    	));
    	$ll_month_count = $this->{$model}->find('count',array(
    		'conditions' => array_merge($conditions,array('created >=' => date('Y-m',strtotime('-2 month')),'created <' => date('Y-m',strtotime('-1 month')) )),
    	    'recursive' => -1,
    	));
    	$this->set('today_count',$today_count);
    	$this->set('yestoday_count',$yestoday_count);
    	$this->set('week_count',$week_count);
    	$this->set('month_count',$month_count);
    	$this->set('last_month_count',$last_month_count);
    	$this->set('ll_month_count',$ll_month_count);
    	$this->set('model',$model);
    }

    function admin_strip_fields($model,$field) {
    	if($GLOBALS['argc'] != 4) {echo "param error";exit;}
        $model = $GLOBALS['argv'][2];
        $field = $GLOBALS['argv'][3];
        echo "\n===$model,$field===\n";

        $pagesize = 100;
        $page = 1;
        App::uses('CrawlUtility', 'Utility');
        $this->loadModel($model);
        do
        {
            $datalist = $this->{$model}->find('all',array(
                'conditions' => array(),
                'fields' => array('id',$field),
                'page' => $page,
                'limit' => $pagesize,
                'recursive' => -1,
            ));
            foreach($datalist as $item) {
                if(empty($item[$model][$field])) { continue; }
                $field_value = strip_tags($item[$model][$field]);
                $field_value = str_replace('&nbsp;',' ',$field_value);  
                $field_value = trim($field_value ); 
                echo "\n=={$item[$model]['id']}====$field_value====\n";
                $this->{$model}->updateAll(array($field=>"'".$field_value."'"),array('id'=> $item[$model]['id']));
            }
            $page ++;
            echo "\n====$page ===$pagesize========\n\n";
        }
        while(count($datalist) == $pagesize);
        echo "over.\n";
        exit;
    }

    function admin_image_to_oss($model,$field) {

        if($GLOBALS['argc'] != 4) {echo "param error";exit;}
        $model = $GLOBALS['argv'][2];
        $field = $GLOBALS['argv'][3];
        echo "\n===$model,$field===\n";

        $pagesize = 100;
        $page = 1;
        App::uses('CrawlUtility', 'Utility');
        $this->loadModel($model);
        do
        {
            $datalist = $this->{$model}->find('all',array(
                'conditions' => array(),
                'fields' => array('id',$field),
                'page' => $page,
                'limit' => $pagesize,
                'recursive' => -1,
            ));
            foreach($datalist as $item) {

                if(strpos($item[$model][$field],'http://') !== false) {
                    continue;
                }
                if(empty($item[$model][$field])) { continue; }

                if(file_exists(UPLOAD_FILE_PATH.$item[$model][$field])) {
                    $file_url = CrawlUtility::saveToAliOss(UPLOAD_FILE_PATH.$item[$model][$field],$item[$model][$field],false);
                    if($file_url) {
                        $this->{$model}->updateAll(array($field=>"'".$file_url."'"),array('id'=> $item[$model]['id']));
                    }
                    print_r($item);
                    echo $file_url."\n";
                }
            }
            $page ++;
            echo "\n====$page ===$pagesize========\n\n";
        }
        while(count($datalist) == $pagesize);
        echo "over.\n";
        exit;
    }
    
    function admin_article_content_oss(){
    	$limit = 5;
    	$page = 1;
    	
    	App::uses('CrawlUtility', 'Utility');
    	do{
    		$this->loadModel('ArticleContent');
    		$results = $this->ArticleContent->find('all',array(
    			'page' => $page,
    			'limit' => $limit,
    		));
    		
    		foreach($results as $item){
    			if($item['ArticleContent']['content']) {
    				if( CrawlUtility::saveToAliOss($item['ArticleContent']['content'], '/article_content/'.$item['ArticleContent']['id'],false,true) ) {
//     					$item['ArticleContent']['content'] = '';
//     					$this->ArticleContent->id = $item['ArticleContent']['id'];
    					$this->ArticleContent->delete($item['ArticleContent']['id']);
    				}
    			}
    			print_r($item);exit;
    		}
    		$page ++;
    	}while(count($results) == $limit);
    	exit;
    }
    
    function admin_dbimport($file='',$volume=1){
    	if(empty($file)){
	    	$backdir = ROOT . '/data/backups/';
	    	$exportvolume = $exportsize = array();
	    	$dir = dir($backdir);
	    	while($entry = $dir->read()) {
	    			if(preg_match("/(.+?)_(\d+)\.sql$/i", $entry,$matches)) {
	    				$key = $matches[1];
	    				if(!isset($exportvolume[$key])){
	    					$exportvolume[$key] = 0;
	    					$exportsize[$key] = 0;
	    				}
	    				$filesize = filesize($backdir.$entry);
	    				$exportlog[$key][] = array(
	    						'volume' => $matches[2],
	    						'filename' => $entry,
	    						'dateline' => filemtime($backdir.$entry),
	    						'size' => $filesize
	    				);
	    				$exportsize[$key] += $filesize;
	    				$exportvolume[$key] +=1;
	    			}
	    	}
	    	$dir->close();
	    	$this->set('exportlog',$exportlog);
	    	$this->set('exportsize',$exportsize);
	    	$this->set('exportvolume',$exportvolume);
    	}
    	else{
    		$dataSourceName = 'default';
    		$dbo = ConnectionManager::getDataSource($dataSourceName);
    		
    		$filename = ROOT . '/data/backups/'.$file.'_'.$volume.'.sql';
    		$content = file_get_contents($filename);
    		$sqls = explode(";\n",$content);
    		
    		foreach($sqls as $sql){
    			$dbo->execute($sql);
    		}
    	}
    }
    /**
     * 数据库导出，分卷.导出第一卷后，页面跳转自动进入下一卷。
     * 使用页面跳转的方式，防止php脚本执行超时
     */
    function admin_dbexport($filename='',$table_start='',$limit_start=0,$volume=1){
    	
    	if(empty($_POST)){
    		
    	}
    	else{
	    	@set_time_limit(0);
	    	$dataSourceName = 'default';
	    	
	    	$path = ROOT . '/data/backups/';
	    	
	    	$Folder = new Folder($path, true);
	    	if(empty($filename)){
	    		$filename = date('Ymd_His').'_'.random_str(6);
	    	}
	    	$fileSufix = $filename.'_'.$volume . '.sql';
	    	
	    	$file = $path . $fileSufix;
	    	if (!is_writable($path)) {
	    		return $this->__message('The path "' . $path . '" isn\'t writable!', 'javascript:void();', 9000);
	    	}
	    	$sql = '';
	    	$limit = 500;
	    	$file_limit_size = 2*1024*1024; //2M
	    	
	    	$File = new File($file);
	    	$config = ConnectionManager::getDataSource($dataSourceName)->config;
	    	$tables = ConnectionManager::getDataSource($dataSourceName)->listSources();
	    	foreach ($tables as $table) {
	    		$table = str_replace($config['prefix'], '', $table);
	    		if(!empty($table_start)){ //$table_start，后续的分卷,不是从第一个表格开始导出
	    			if($table!=$table_start){
	    				continue; // 与开始导出的表格不一样时，跳过这个表格
	    			}
	    			else{
	    				$table_start=''; //仅传参的第一次循环生效，将其置空，阻止第二次生效
	    			}
	    		}
	    		
	    		$ModelName = Inflector::classify($table);
	    		if($ModelName=='I18n'){
	    			$ModelName = 'I18nModel';
	    		}
	    		$Model = ClassRegistry::init($ModelName);
	    		
	    		if(!$Model instanceof Model){
	    			continue;//'I18n'
	    		}
	    		$DataSource = $Model->getDataSource();
	    	
	    		$CakeSchema = new CakeSchema();
	    		$CakeSchema->tables = array($table => $Model->schema());
	    		
	    		$tablename = $DataSource->fullTableName($table);
	    		
	    		/* 创建表格语句 */
	    		if($limit_start==0){
	    			$sql .= "\nDROP TABLE IF EXISTS {$tablename};\n";
	    			$sql .= $DataSource->createSchema($CakeSchema, $table) . "\n";
	    		}
	//     		$File->write("\n/* Backuping table data {$table} */\n");
				
	    		$total = $Model->find('count', array('recursive' => -1));
	    		unset($valueInsert, $fieldInsert);
	    		/* 插入数据 */
	    		while(strlen($sql)<$file_limit_size && $limit_start<$total){
	    			$page = intval($limit_start/$limit)+1;
		    		$rows = $Model->find('all', array('recursive' => -1,'limit'=>$limit,'page'=>$page));
		    		$limit_start +=$limit;
		    		$size = count($rows);
		    		if ($size > 0) {
		    			$fields = array_keys($rows[0][$ModelName]);
		    			//$values = array_values($rows);
		    			$count = count($fields);
		    	
		    			for ($i = 0; $i < $count; $i++) {
		    				$fieldInsert[] = $DataSource->name($fields[$i]);
		    			}
		    			$fieldsInsertComma = implode(', ', $fieldInsert);
		    			
		    			$f_values = array();
		    			foreach ($rows as $k => $row) {
		    				unset($valueInsert);
		    				for ($i = 0; $i < $count; $i++) {
		    					$valueInsert[] = $DataSource->value($row[$ModelName][$fields[$i]], $Model->getColumnType($fields[$i]), false);
		    				}
		    				$f_values[] = '('.implode(', ', $valueInsert).')';
		    				if(count($f_values)>=200){
			    				$sql.= 'INSERT INTO '.$tablename.' ('.$fieldsInsertComma.') VALUES '.implode(",\n", $f_values).";\n";
			    				unset($f_values);$f_values = array();
		    				}
		    			}
		    			if(!empty($f_values)){
		    				$sql .= 'INSERT INTO '.$tablename.' ('.$fieldsInsertComma.') VALUES '.implode(",\n", $f_values).";\n";
		    				unset($f_values);
		    			}
		    		}
		    		if($size < $limit){
		    			$limit_start = 0; // 当查出的行数小于limit数时，重置limit_start为0。当前表格数据处理完成
		    			break;
		    		}
	    		} // end while. loop export data.
	    		if($limit_start>=$total){
	    			$limit_start = 0;
	    		}
	    		
	    		if(strlen($sql) >= $file_limit_size){
	    			$File->write($sql);
	    			$File->close();
	    			unset($sql);
	    			$this->__message('正在备份分卷'.$volume, array('action'=>'dbexport',$filename,$table,$limit_start,$volume+1), 5);
	    		}
	    	} // end foreach
	    	if(!empty($sql)){
	    		$File->write($sql);
	    		$File->close();
	    		unset($sql);
	    	}
	    	
	    	return $this->__message('备份完成', array('action'=>'dbimport'), 90);
    	}
    }
    
/*-----------------------------------------------------------------------------*/    
    
    
    /***
     * set visible to 1,
     
    function admin_activestyle($id){
    	$parent_info = $this->Misccate->findById(160);
    	//     	$parent_info = $this->Misccate->findBySlug('styles'); // styles 对应的数据id为160
    	//     	$parent_id = $parent_info['Misccate']['id'];
    	$left = $parent_info['Misccate']['left'];
    	$right = $parent_info['Misccate']['right'];
    	$conditions = array('Misccate.left >' => $left,'visible'=>1,'Misccate.right <' => $right);
    	$styles = $this->Misccate->find('all', array('conditions' => $conditions, 'order' => 'left asc'));
    }*/
    
    /**
     * 创建模板文件夹
     */
    function admin_createThemeFolder(){
    	if($_POST['type']=='admin'){
    		$path = VIEWS.'/Themed/'.$_POST['name'];
    	}
    	else{
    		$path = SITE_VIEWS.'/Themed/'.$_POST['name'];
    	}
    	$Folder = new Folder($path, true);
    	
    	if(file_exists($path)){
    		$resultinfo = array('success' => __('create folder %s success',$path));
        } else {
            $resultinfo = array('error' => __('create error.make sure %s is writeable',$path));
        }
        echo json_encode($resultinfo);
    	exit;
    }
        
    /**
     * 设置所使用的模版套系
     * Site.theme
     * Admin.theme
     */
    function admin_themes(){
    	$dir = SITE_VIEWS.'./Themed/';
    	$templatedir = dir($dir);
    	$sitetpls = array();
    	while($entry = $templatedir->read()) {
    		$tpldir = realpath($dir.'/'.$entry);
    		if(!in_array($entry, array('.', '..')) && is_dir($tpldir)) {
    			$sitetpls[] = array(
    					'name' => $entry,
    					'time' => date('Y-m-d H:i:s',@filemtime($dir.'/'.$entry))
    			);
    		}
    	}
    	
    	$dir = VIEWS.'./Themed/';
    	$templatedir = dir($dir);
    	$tpls = array();
    	while($entry = $templatedir->read()) {
    		$tpldir = realpath($dir.'/'.$entry);
    		if(!in_array($entry, array('.', '..')) && is_dir($tpldir)) {    			
    			$tpls[] = array(
    					'name' => $entry,
    					'time' => date('Y-m-d H:i:s',@filemtime($dir.'/'.$entry))
    			);
    		}
    	}
    	
    	$site_theme = Configure::read('Site.theme');
    	
    	$admin_theme = Configure::read('Admin.theme');
    	
    	$mobile_theme = Configure::read('Site.mobile_theme');
    	
    	$this->set(array('sitetpls'=>$sitetpls,'tpls'=>$tpls,'site_theme'=>$site_theme,'mobile_theme'=>$mobile_theme,'admin_theme'=>$admin_theme));
    }
    
/*-----------------------------------------------------------------------------*/    
    /**
     * PHP探针 
     **/
    function admin_tz(){
    	include APP_PATH.'tz.php';
    	exit;
    }
    
    /*
     * not safe
     *
     * public function admin_runsql(){
    	if( !empty($this->data['Tool']['sql']) ) {
    		$this->loadModel('User');
    		$this->User->query($this->data['Tool']['sql']);
    		unset($this->data['Tool']['sql']);
    		
    		CakeLog::info("Run SQL:".$this->data['Tool']['sql']);
    		
    		$this->set('resultinfo', array(
    			'success'=> __('Run SQL Success.'),
    		));
    		$this->set('_serialize', 'resultinfo');
    	}
    }*/
    
    public function admin_email(){
    	if(!empty($_POST)){
    		
    		$this->loadModel('Template');
    		if($this->data['Tool']['save_type']==1){ //save new
    			$this->Template->create();
    			$this->Template->save(array(
    					'name'=>$this->data['Tool']['name'],
    					'content'=>$this->data['Tool']['content'],
    					'model' => 'email'
    			));
    		}
    		elseif( $this->data['Tool']['save_type']==2 ){ //update
    			$this->Template->save(array(
    					'id'=> $this->data['Tool']['template_id'], 
    					'name'=>$this->data['Tool']['name'],
    					'content'=>$this->data['Tool']['content'],
    					'model' => 'email'
    			));
    		}
    		
    		App::uses('EmailUtility', 'Utility');
    		$email_sender = new EmailUtility();
    		
    		$email_options = array(
    				'to' => explode(';',$this->data['Tool']['email']),
    				'subject' => '[' . Configure::read('Site.title') . '] '.$this->data['Tool']['name'],
    				'template' => 'content',
    				'viewVars' => array( 'email_content'=> $this->data['Tool']['content'] ),
    		);
    		
    		if($ret = $email_sender->send($email_options)){
    			$this->set('resultinfo', array(
    					'success'=> __('Send email success.'),
    			));
    			$this->set('_serialize', 'resultinfo');
    			// status 记录成功状态  event_handle_logs(id,handle_name,handle_id,event_id, status,updated,times)
    		}
    		else{
	    		$this->set('resultinfo', array(
	    				'error'=> __('Send email error.'),
	    		));
	    		$this->set('_serialize', 'resultinfo');
    		}
    		// send email.
    		//exit;
    	}
    	$this->loadModel('Template');
    	$email_templates = $this->Template->find('list',array('conditions'=>array('model'=>'email')));
    	
    	array_unshift($email_templates,__('Please Select'));
    	
    	$this->set('email_templates',$email_templates);
    }
    
    /**
     * SAE KVDB管理页
     **/
    function admin_saekv(){
    	include APP_PATH.'saekv.php';
    	exit;
    }
    
    function admin_updatePw(){
    	$this->autoRender = false;
		$argv = $GLOBALS ['argv'];
    	if(php_sapi_name()==='cli' && count($argv)==4) {
	    	$passwd = Security::hash($argv[3], null, true);
	    	$staffid = $argv[2];
	    	$this->loadModel('Staff');	    	
	    	$this->Staff->updateAll(array('password' => "'$passwd'"),array('id'=>$staffid));
	    	echo "\nover\n\n";
	    	exit;
    	}
    	echo "\nphp index.php /admin/tools/updatePw staffid passwd\n\n";
		exit;
    	
    }
    
    function admin_clearCoreCache(){
    	Cache::clear(false, '_cake_core_');
    	clearFolder(DATA_PATH.DS.'cache'.DS.'persistent',true);
    	
    	Cache::clear(false, '_cake_model_');
    	clearFolder(DATA_PATH.DS.'cache'.DS.'models',true);
    	 
    	if ($this->RequestHandler->accepts('json') || $this->RequestHandler->isAjax() || isset($_GET['inajax'])) {
    		$this->autoRender = false;
    		echo json_encode(array('success' => __('Clear Core Cache Success')));
    		exit;
    	}
    	else{
    		$this->__message(__('Clear Core Cache Success'), '', 99999);
    	}
    }
    
    function admin_clearRunCache(){
    	Cache::clear(false, 'default');
    	clearFolder(DATA_PATH.DS.'cache',false);
    	if ($this->RequestHandler->accepts('json') || $this->RequestHandler->isAjax() || isset($_GET['inajax'])) {
    		$this->autoRender = false;
    		echo json_encode(array('success' => __('Clear Run Cache Success')));
    		exit;
    	}
    	else{
    		$this->__message(__('Clear Run Cache Success'), '', 99999);
    	}
    }
    
    function admin_clearViewCache(){
    	clearFolder(DATA_PATH.DS.'cache'.DS.'views',true);
    	if ($this->RequestHandler->accepts('json') || $this->RequestHandler->isAjax() || isset($_GET['inajax'])) {
    		$this->autoRender = false;
    		echo json_encode(array('success' => __('Clear View Cache Success')));
    		exit;
    	}
    	else{
    		$this->__message(__('Clear View Cache Success'), '', 99999);
    	}
    }
    
    function admin_rewriteSetting(){
    	$this->autoRender = false;
    	$this->loadModel('Setting');
    	$this->Setting->writeConfiguration(true);
    	echo json_encode(array('ret'=>0,'msg' => __('Rewrite settings file success')));
    }

    /**
     * 清空缓存,需要同时删除app及manage项目生成的缓存
     */
    function admin_clearcache(){
    	$this->autoRender = false;
    	clearCacheAll();
    	/*更新语言包缓存*/
        $this->_updateDefinedLanguage();
        
        $this->loadModel('Setting');
        $this->Setting->writeConfiguration(true); // 更新settings.php
        
        /****     requestAction在使用admin.php rewrite访问时，requestAction自动访问到index.php了，造成错误       ****/
        $this->admin_updateLanCache('zh-cn',true);
        $this->admin_updateLanCache('en-us',true);
    	// $this->requestAction('/admin/tools/updateLanCache',array('data'=>array('uplang'=>'zh-cn')));
    	// $this->requestAction('/admin/tools/updateLanCache',array('data'=>array('uplang'=>'en-us')));
        if ($this->RequestHandler->accepts('json') || $this->RequestHandler->isAjax() || isset($_GET['inajax'])) {
        	$this->autoRender = false;
        	echo json_encode(array('ret'=>0,'msg' => __('Clear Cache Success')));
        	exit;
        }
        else{
        	$this->__message(__('Clear Cache Success'), '', 99999);
        }
    }

    /**
     * 生成链接的slug别名
     */
    function admin_genSlug() {
    	App::uses('Charset', 'Lib');
    	App::uses('Pinyin', 'Lib');
    	$PY = new Pinyin();
    	$slug = $PY->stringToPinyin(Charset::utf8_gbk($_REQUEST['word']),'-');
        $slug = Inflector::slug($slug);
        $slug = substr(str_replace('_','-',$slug),0,255);

        if($slug && $_REQUEST['model']) {
        	$this->loadModel($_REQUEST['model']);
        	$haved = $this->{$_REQUEST['model']}->find('first',array(
        		'conditions' => array('slug'=>$slug),
			));
        	if($haved) { //若已经重复时，取消自动生成，需手动设置。
        		$slug = '';
			}
		}

        $this->autoRender = false;
        echo json_encode(array('slug' => $slug));
        exit;
    }

    public  function _updateDefinedLanguage(){
        try{
            $cache_all = array();

            // 获取对应的地域名称
            $I18n = I18n::getInstance();
            $I18n->l10n->get(Configure::read('Site.language'));
            $locale_alias = $I18n->l10n->locale;

            // 获取第一个locale文件夹，
            if (!class_exists('I18n')) {
                App::uses('I18n', 'I18n');
            }
            $locals = App::path('locales');
            $local_path = array_shift($locals);

            
            $system_language = Configure::read('System.ActiveLanguage');

            $this->autoRender = false;
            //$language_id = Configure::read('Site.DefaultLanguageId');
            $this->loadModel('DefinedLanguage');
            if( is_array($system_language) && !empty($system_language) ) {
                foreach($system_language as $alias => $slang){
    
                    $language_id = $slang['id'];
                    $locale_alias = getLocal($alias);
    
                    $languages = $this->DefinedLanguage->find('all',array(
                        'conditions' => array('language_id' => $language_id)
                    ));
                    
                    foreach($languages as $item){
                        if(!empty($item['DefinedLanguage']['value'])){
                            $cache_all[$item['DefinedLanguage']['key']] = $item['DefinedLanguage']['value'];
                        }
                    }
                    $filename = $local_path . $locale_alias . DS . 'default.php';
                    
                    $file_contnets = "<?php\ndefine('LANGUAGE_DEFAULT',true);\n return ".var_export($cache_all,true).";\n";
                    if(defined('IN_SAE')){
                        file_put_contents($filename, $file_contnets);
                    }
                    else{
                        $file = new File($filename, true);
                        $file->write($file_contnets);
                    }
                }
            }
            
            return true;
        }
        catch(Exception $e)
        {
            print_r($e);
            return false;
        }

    }
    /**
     * 更新语言包的缓存
     */
    function admin_updateLanCache($uplang='zh-cn',$return = false) {
//    		$locals = App::path('locales'); print_r($locals);exit;

        if(empty($uplang)){
            $uplang = $this->data['uplang'] ? 'uplang':$_REQUEST['uplang'];
        }
        if(!$return){
            $return = $this->params['return'];
        }
		
        if (empty($uplang)) {
            $this->loadModel('Language');
            $lans = $this->Language->find('all');
            $selectlans = array();
            foreach ($lans as $lang) {
                $selectlans[$lang['Language']['alias']] = $lang['Language']['native'];
            }
            $this->set('selectlans', $selectlans);
        } else {
            Configure::write('Site.language', $uplang);
            // 获取对应的地域名称
            $I18n = I18n::getInstance();
            $I18n->l10n->get(Configure::read('Site.language'));
            $locale_alias = $I18n->l10n->locale;

            // 获取第一个locale文件夹，
            if (!class_exists('I18n')) {
                App::uses('I18n', 'I18n');
            }
            $locals = App::path('locales');
            $local_path = array_shift($locals);

            App::uses('File', 'Utility');

            $this->loadModel('I18nfield');
            $fields = $this->I18nfield->find('all');
            $file_contnets = '';
            foreach ($fields as $key => $value) {
                $file_contnets .= 'msgid "' . $value['I18nfield']['model'] . '_' . $value['I18nfield']['name'] . "\"\r\n";
                $file_contnets .= 'msgstr "' . str_replace('"', '\"', $value['I18nfield']['translate']) . "\"\r\n";
            }
            $filename = $local_path . $locale_alias . DS . 'LC_MESSAGES' . DS . 'i18nfield.po';
            if(defined('IN_SAE')){
            	file_put_contents($filename, $file_contnets);
            }
            else{
	            $file = new File($filename, true);
	            $file->write($file_contnets);
            }

            $this->loadModel('Modelextend');
            $fields = $this->Modelextend->find('all');
            $file_contnets = '';
            foreach ($fields as $key => $value) {
                $file_contnets .= 'msgid "' . $value['Modelextend']['name'] . "\"\r\n";
                if($uplang == 'en-us'){
                	$file_contnets .= 'msgstr "' . str_replace('"', '\"', $value['Modelextend']['name']) . "\"\r\n";
                }
                elseif($uplang == 'zh-cn'){
                	$file_contnets .= 'msgstr "' . str_replace('"', '\"', $value['Modelextend']['cname']) . "\"\r\n";
                }
            }
            
            $filename = $local_path . $locale_alias . DS . 'LC_MESSAGES' . DS . 'modelextend.po';
            if(defined('IN_SAE')){
            	file_put_contents($filename, $file_contnets);
            }
            else{
	            $file = new File($filename, true);
	            $file->write($file_contnets);
            }
            $resultinfo = array('success' => __('Edit success'));
            $this->autoRender = false;
            if($return){
            	return $resultinfo;
            }
            else{
            	echo json_encode($resultinfo);
            }
        }
    }

    function admin_startseo() {
        $models = explode(',', Configure::read('Admin.contentmodels'));
        $content_models = array();
        foreach ($models as $v) {
            $content_models[$v] = __('model_' . $v);
        }
        $this->set('content_models', $content_models);
    }

    /**
     * 生成SEO数据
     * @param $modelname
     * @param $page
     * @param $pagesize
     */
    function admin_autoseo($modelname='', $page=1, $pagesize=10, $autonext = 0) {

        if ($this->data['Tool']['modelname']) {
            $modelname = $this->data['Tool']['modelname'];
        }
        //print_r($this->data);exit;
        $this->loadmodel($modelname);

        $this->{$modelname}->recursive = 1;
        $options = array(
            'limit' => $pagesize,
            'page' => $page,
            'order' => 'id desc'
        );
        $controlname = Inflector::pluralize($modelname);
        $datas = $this->{$modelname}->find('all', $options);

        $this->loadmodel('KeywordRelated');

        foreach ($datas as $data) {
            if ($data[$modelname]['content']) { //分词，并保存入库
                $keywords = $this->WordSegment->segment($data[$modelname]['content']);
                if (empty($keywords))
                    continue;
                $seokeywords = array();
                $mainkeywords = array();
                $i = 0;
                foreach ($keywords as $k => $v) {
                    if ($i < 5) {
                        $mainkeywords[$k] = $v;
                    }
                    if ($i < 20) {
                        $seokeywords[$k] = $v;
                    } else {
                        break;
                    }
                    $i++;
                }
                $seodata = array();
                $seodata['seokeywords'] = $sv_seokeywords = implode(',', $seokeywords); // 20个词作为seokeywords
                $seodata['keywords'] = $sv_keywords = implode(',', $mainkeywords); // 5个词作为keywords
                $seodata['id'] = $data[$modelname]['id'];
                $this->{$modelname}->save($seodata);
                // 修改表中关键字
//				$this->{$modelname}->updateAll(
//					array('seokeywords'=> $sv_seokeywords,'keywords'=>$sv_keywords),
//					array('id'=> $data[$modelname]['id'])
//				);
                // 更新key_related中相关的记录
                $this->KeywordRelated->deleteAll(array('relatedid' => $data[$modelname]['id'], 'relatedmodel' => $modelname), true, true);
                foreach ($mainkeywords as $key => $value) {
                    $this->KeywordRelated->create();
                    $keyword_related['relatedid'] = $data[$modelname]['id'];
                    $keyword_related['relatedmodel'] = $modelname;
                    $keyword_related['keyword_id'] = $key;
                    $this->KeywordRelated->save($keyword_related);
                }
            }
        }
        if (empty($datas) || count($datas) < $pagesize) {
            $this->__message(__("seo do over", true), array('action' => 'startseo'), 99999);
        }
        $nextpage = $page + 1;
        $this->__message(__("page %s Done", $page), array('action' => 'autoseo', $modelname, $nextpage, $pagesize), 3);
    }

}

?>
